package com.ubxtech.websocket.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ubxtech.core.context.ContextConstants;
import com.ubxtech.core.context.ContextToken;
import com.ubxtech.core.context.ContextUtil;
import com.ubxtech.websocket.util.SocketUtil;
import lombok.extern.slf4j.Slf4j;

import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * @author Victor.Xiao
 * @since 2023-12-09 11:47
 **/
@Slf4j
public class WebSocketConfigurator  extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {

        Map<String, List<String>> header = request.getHeaders();
        Map<String, List<String>> parameterMap = request.getParameterMap();
        String token = getHeader(header, ContextConstants.TOKEN);
        String userId = getHeader(header, ContextConstants.USER_ID);
        String userName = getHeader(header, ContextConstants.USERNAME);
        String tenant = getHeader(header, ContextConstants.KEY_TENANT);
        if (StrUtil.isBlank(token) || StrUtil.isBlank(userId)) {
            return;
        }
        ContextToken contextToken = new ContextToken();
        contextToken.setToken(token);
        contextToken.setUserId(userId);
        contextToken.setUsername(userName);
        contextToken.setTenant(tenant);
        ContextUtil.setContextToken(contextToken);
        ContextUtil.set(SocketUtil.WEBSOCKET_PARAM, parameterMap);
    }

    private String getHeader(Map<String, List<String>> header ,String headerName) {
        if (CollectionUtil.isEmpty(header)) {
            return "";
        }
        if (header.get(headerName) != null && CollectionUtil.isNotEmpty(header.get(headerName))) {
            return header.get(headerName).get(0);
        }
        return "";
    }
}
